// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.apache.doris.rewrite;


import org.apache.doris.analysis.Analyzer;
import org.apache.doris.analysis.BinaryPredicate;
import org.apache.doris.analysis.BinaryPredicate.Operator;
import org.apache.doris.analysis.CastExpr;
import org.apache.doris.analysis.IntLiteral;
import org.apache.doris.analysis.SlotDescriptor;
import org.apache.doris.analysis.SlotId;
import org.apache.doris.analysis.SlotRef;
import org.apache.doris.catalog.Type;
import org.apache.doris.common.AnalysisException;
import org.apache.doris.rewrite.ExprRewriter.ClauseType;

import mockit.Mocked;
import org.junit.Assert;
import org.junit.Test;

public class RewriteImplicitCastRuleTest {

    @Test
    public void testRewriteCastString(@Mocked Analyzer analyzer) throws AnalysisException {
        RewriteImplicitCastRule rule = new RewriteImplicitCastRule();
        IntLiteral tinyIntLiteral = new IntLiteral(1);
        SlotId id = new SlotId(0);
        SlotDescriptor slotDesc = new SlotDescriptor(id, null);
        slotDesc.setType(Type.INT);
        SlotRef slotRef = new SlotRef(slotDesc);
        slotRef.setType(Type.INT);
        BinaryPredicate binaryPredicate = new BinaryPredicate(Operator.EQ, slotRef.castTo(Type.BIGINT), tinyIntLiteral);
        rule.apply(binaryPredicate, analyzer, ClauseType.WHERE_CLAUSE);
        Assert.assertTrue(binaryPredicate.getChild(1) instanceof IntLiteral);
        Assert.assertEquals(binaryPredicate.getChild(1).getType(), Type.INT);
        Assert.assertSame(binaryPredicate.getChild(0), slotRef);

        IntLiteral smallIntLiteral = new IntLiteral(IntLiteral.SMALL_INT_MAX);
        slotRef.setType(Type.TINYINT);
        binaryPredicate = new BinaryPredicate(Operator.EQ, slotRef.castTo(Type.BIGINT), smallIntLiteral);
        rule.apply(binaryPredicate, analyzer, ClauseType.WHERE_CLAUSE);
        Assert.assertTrue(binaryPredicate.getChild(0) instanceof CastExpr);
    }

}
